package com.apestech.framework.sql.table;

import com.apestech.framework.cache.Cache;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.condition.ConditionMap;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.sql.modul.SqlList;
import com.apestech.framework.util.ExceptionUtil;

/**
 * @author hup
 * @create 2018-08-30-11:55
 */
public class TableInsert extends SqlUtil {

    private String sql;
    private ConditionMap param;
    private SqlList sqlparam=new SqlList();
    private String colValue="";
    private String schema;

    public TableInsert(ConditionMap param) throws Exception {
        this.param=param;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public void getTableSql() throws Exception {
        sqlparam=new SqlList();
        sql= (String) Cache.getKey(param.getCacheKey());
        if(sql==null){
            sql=getInsert();
            sqlparam=new SqlList();
            Cache.setKey(param.getCacheKey(), sql);
        }
        String where=param.getExecSql();
        if(where!=null) where=where.trim();
        if(where==null || "".equals(where)){
            if("".equals(colValue)){
                String s=sql.substring(sql.indexOf("(")+1, sql.indexOf(")"));
                colValue="#{"+s.replace(",","},#{")+"}";
            }
            sql=sql+" VALUES ("+colValue+")";
        }
        else sql=sql+where;
        sql=addSql(param.getFromtab(), sql, param, sqlparam, "");
    }

    public String getInsert() throws Exception {
        try {
            String tabName=param.getFromtab().getTabName();
            if(schema!=null) tabName=schema+"."+tabName;
            Table table=param.getFromtab().getTable();
            String filter=param.getSqlruleFields(tabName);
            boolean in=!param.getSqlruleNotIn(tabName);
            String col=getCol(table.getColumn(), filter, in);
            if("".equals(col)){
                return null;
            }
            colValue="#{"+col.replace(",","},#{")+"}";
            sql=" INSERT INTO "+tabName+"("+col+") ";
            return sql;
        } catch (Exception e) {
            ExceptionUtil.exception(this, "getInsert", e.getMessage());
        }
        return null;
    }

    public SqlList getSqlparam() {
        return sqlparam;
    }

    public String getSql() {
        return sql;
    }
}
